package com.hduong.springcloud.controller;

import com.hduong.springcloud.lb.LoadBalancer;
import entities.CommonResult;
import entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * Created by dudu on 2020/3/17.
 */
@RestController
@Slf4j
public class OrderController {

//    public static final String PAYMENY_URL = "http://localhost:8001";
    //默认使用唯一的服务名称去进行 负载均衡
    public static final String PAYMENY_URL = "http://BEFORE-CLOUD-PAYMENT-SERVICE/";

    @Autowired
    RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

//    @PostMapping("/consumer/payment/create")
//    public CommonResult<Payment> create(Payment payment) {
//        return restTemplate.postForEntity(PAYMENY_URL + "payment/create", payment,CommonResult.class);
//    }
    @PostMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENY_URL + "payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PAYMENY_URL + "payment/get/"+id, CommonResult.class);
    }

    @GetMapping("/consumer/payment/port")
    public CommonResult getPort() {
        return restTemplate.getForObject(PAYMENY_URL + "payment/getPort", CommonResult.class);
    }

    @GetMapping(value = "/consumer/payment/lb")
    public CommonResult getPaymenyUrl() {
//        List<String> services = discoveryClient.getServices();

        List<ServiceInstance> instances = discoveryClient.getInstances("BEFORE-CLOUD-PAYMENT-SERVICE");
        if(instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/payment/lb", CommonResult.class);
    }

}
